package com.jctrip.hotel.route.config;


import com.jctrip.hotel.route.model.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice(basePackages = "com.jctrip.hotel.route")
public class RouteControllerAdvice {

    /**
     * 接口参数校验异常捕捉
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> validatorException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult()
                .getAllErrors()
                .stream()
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.joining(","));
        return Result.error(message);
    }

    /**
     * 系统异常捕捉
     */
    @ExceptionHandler(Exception.class)
    public Result<Void> defaultException(Exception e) {
        log.error("系统异常：" + e.getMessage(), e);
        return Result.error(e.getMessage());
    }
}
